<template>
  <div>
    <el-card class="top">
      <el-button type="primary" @click="addBroker">添加经纪</el-button>
      <el-input
        v-model="name_contains"
        class="input"
        placeholder="请搜索经纪名称"
      />
      <el-button type="success" @click="searchFn">搜索</el-button>
    </el-card>
    <el-card>
      <!-- 表格主体 -->
      <el-table :data="agentList" border>
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <img class="img" :src="row.image" alt="">
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="name" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="电话" prop="phone" />
        <el-table-column label="地址" prop="address" />
        <el-table-column label="介绍" prop="desc" />

        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button size="mini" @click="editAgent(row.id)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="delFn(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="block">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageConfig._limit"
          @current-change="currentChangeFn"
        />
      </div>

      <!-- diaolog弹窗 -->
      <el-dialog
        v-if="isShowDialog"
        :title="addAgentList.id ? '编辑经纪人' : '新增经纪人'"
        :visible="isShowDialog"
        @close="cancleFn"
      >
        <el-form ref="agentForm" :rules="rules" :model="addAgentList">
          <el-form-item label="名称" prop="name">
            <el-input v-model="addAgentList.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="addAgentList.email"
              placeholder="请输入邮箱,必须为带'@'格式,3~30位"
            />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="addAgentList.phone" placeholder="请输入电话" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="addAgentList.address" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="addAgentList.desc" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item label="封面" prop="image">
            <!-- 头像上传插件,要下载腾讯云依赖 -->
            <ImageUpload ref="upload" />
          </el-form-item>

          <div>
            <el-button
              class="btn"
              size="small"
              @click="cancleFn"
            >取消</el-button>
            <el-button
              type="primary"
              size="small"
              @click="confirmFn"
            >确定</el-button>
          </div>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getAgents,
  getAgentsTotal,
  addAgent,
  delAgent,
  getAgentById,
  editAgent
} from '@/api/agents.js'
import ImageUpload from '@/views/agents/components/imageUpload'
export default {
  components: { ImageUpload },
  data() {
    return {
      isShowDialog: false, // 控制弹窗显隐
      agentList: [], //  经纪人列表
      //  分页配置
      pageConfig: {
        _limit: 5, // 每页长度
        _start: 0 //  从几号下标开始显示
      },
      name_contains: '', // 搜索框输入内容

      total: 0, // 经纪人总数

      // 添加经纪人列表
      addAgentList: {
        name: '', // 姓名
        email: '', // 邮箱
        phone: '', //  电话
        address: '', //  地址
        desc: '', //  描述
        image: '' //  头像（腾讯云线上路径）
      },

      rules: {
        name: [{ required: true, message: '姓名不能为空！', trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱不能为空！', trigger: 'blur' },
          {
            min: 3,
            max: 30,
            message: '邮箱必须带@符号,长度为3~30位',
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '手机号不能为空！', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空！', trigger: 'blur' }
        ],
        desc: [{ required: true, message: '描述不能为空！', trigger: 'blur' }]
      }
    }
  },
  async created() {
    this.getAgentsList()
    // 获取经纪人总数
    this.total = await (await getAgentsTotal()).data
  },
  methods: {
    // 获取经纪人列表
    async getAgentsList() {
      const res = await getAgents(this.pageConfig)
      this.agentList = res.data
    },

    // 页码变化，触发函数
    async currentChangeFn(newPage) {
      this.pageConfig._start = (newPage - 1) * this.pageConfig._limit
      // 重新获取经纪列表
      this.agentList = await (
        await getAgents({
          ...this.pageConfig,
          name_contains: this.name_contains
        })
      ).data
    },

    // 新增经纪人(弹窗)
    addBroker() {
      this.isShowDialog = true
      // this.$nextTick(() => {
      //   console.log(140, this.$refs.upload.filelist[0].url);
      // });
    },

    // 确定新增
    async confirmFn() {
      // validate()  表单校验通过后，才执行下方代码
      this.$refs.agentForm.validate()

      // 判断是新增还是编辑
      if (this.addAgentList.id) {
        // 编辑
        // 获取修改后在线图片地址，注意从upload组件中获取
        this.addAgentList.image = this.$refs.upload.filelist[0].url
        const res = await editAgent(this.addAgentList)
        // 弹窗显示（结果）
        if (res.request.status === 200) {
          this.$message.success('编辑成功！')
        } else {
          this.$message.error('编辑失败！')
        }
      } else {
        // 新增
        // 获取子组件中的数据（图片的在线地址）
        this.addAgentList.image = this.$refs.upload.filelist[0].url
        const res = await addAgent(this.addAgentList)
        // 弹窗显示（结果）
        if (res.request.status === 200) {
          this.$message.success('新增成功！')
        } else {
          this.$message.error('新增失败！')
        }
      }

      // 刷新列表
      this.getAgentsList()
      this.isShowDialog = false
    },

    // 编辑经纪人 ( 数据回显 )
    async editAgent(id) {
      this.isShowDialog = true
      const res = await getAgentById(id)
      this.addAgentList = res.data
      // console.log(this.$refs.upload.filelist);

      // 获取在线地址，发回给子组件，回显头像，直接赋值 filelist 长度为0
      const obj = {}
      obj.url = this.addAgentList.image
      // console.log(208,obj);
      this.$refs.upload.filelist.push(obj)
    },

    // 关闭、取消按钮
    cancleFn() {
      this.isShowDialog = false
      // 清空输入框，用于弹框title动态切换
      this.addAgentList = {}
      // 清空校验规则
      this.$refs.agentForm.resetFields()
    },

    // 搜索功能
    async searchFn() {
      // 强制跳转到第一页
      this.pageConfig._start = 0
      const res = await getAgents({
        ...this.pageConfig,
        name_contains: this.name_contains
      })
      this.agentList = res.data

      // 根据搜索内容，动态显示分页器
      if (this.name_contains) {
        this.total = await (
          await getAgentsTotal({ name_contains: this.name_contains })
        ).data
      } else {
        this.total = await (await getAgentsTotal()).data
      }
    },

    // 删除经纪人
    delFn(id) {
      this.$confirm('将永久删除经纪人, 是否确定?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 点确定，触发then ---- 点取消，触发catch
        .then(async() => {
          // 调用删除接口
          await delAgent(id)
          // 轻提示
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新列表
          this.getAgentsList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.input {
  width: 400px;
  margin-left: 400px;
}
.top {
  display: flex;
  justify-content: space-around;
}
.block {
  margin-top: 18px;
  text-align: center;
}
.el-input {
  width: 350px;
  margin-left: 55px;
}
.img {
  width: 80px;
}
.btn {
  margin-left: 300px;
}
</style>
